#!/usr/local/bin/python
# -*- coding: utf-8 -*-

'''
    辅助方法定义
'''

import Queue, threading

from datetime import date, timedelta
import time

import logging, traceback
from tornado.escape import json_encode,json_decode
import random
from tornado import httpclient
import urllib,urllib2
import code_define
import log
import const

logger = logging.getLogger(__name__)

#--------
g_map_process_func = {}

#--------
def registMethod(methodName, func = None):
    '''注册方法'''
    global g_map_process_func    
    if func is None:
        logger.print_warning(logger, "registMethod, func:[%s] is null" % methodName)
        return    
    if g_map_process_func.has_key(methodName):
        log.print_warning(logger, "registMethod: func:[%s] has exists.." % methodName)
        return
    log.print_debug(logger, "registMethod, func:[%s]" % methodName)
    g_map_process_func[methodName] = func

#--------
def onDoMethod(methodName, request, content):
    '''命令分发'''
    global g_map_process_func
    print "@@1@@命令分发>", methodName, request, content
    tempFunc = None
    if g_map_process_func.has_key(methodName):
        tempFunc = g_map_process_func[methodName]
    if tempFunc is None:    
        log.print_error(logger, "onDoMethod, func:[%s] is None." % methodName)
        return -1
    else:
        log.print_debug(logger, "onDoMethod, func:[%s] will exec" % methodName)
        return tempFunc(request, content) #执行


#---日期是否跟当前时间间隔 < tmpDistanceDay天
def isDayDistance(tmpStrDay, tmpDistanceDay):
    if not tmpStrDay:
        return False 
    tmpStructTime = time.strptime(tmpStrDay[0:10], '%Y-%m-%d')
    
    tmpDate = date(tmpStructTime.tm_year, tmpStructTime.tm_mon, tmpStructTime.tm_mday)
    tmpTimedelta = date.today() - tmpDate
    return tmpTimedelta.days < tmpDistanceDay
    
#--------
def getTimeSecondToStr(iTimeSecond):
    '''把秒转换成日期格式'''
    return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(iTimeSecond))

#--------
def getCurrentDatetimeToStr():
    '''获取当前时间'''
    return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))  

#--------
def getKeysFromMap(tmpMap, tmpCount):
    '''从map获取一定数量的keys队列'''
    tmpLen = len(tmpMap)   
    if tmpCount >= tmpLen:
        return tmpMap.keys()
    
    tmpRand = random.randint(1, tmpLen)
    log.print_debug(logger, "getKeysFromMap, mapLen:[%s], requestCount:[%s], mpRand:[%s]" % (tmpLen, tmpCount, tmpRand))
    
    f = tmpLen - tmpCount
    e = tmpLen - tmpRand
    b = tmpCount - e
    
    tmpKeys =  tmpMap.keys()
    tmpReturn = [] 
    if tmpRand > f:
        tmpReturn = tmpKeys[tmpRand:]+ tmpKeys[:b]
    else:
        tmpReturn = tmpKeys[tmpRand: (tmpLen+b)]
    return tmpReturn
    
    
def getRandomFromList(tmpList, tmpCount):
    '''从列表获取一定数量队列'''
    tmpLen = len(tmpList)      
    if tmpCount >= tmpLen:
        return tmpList
    
    tmpRand = random.randint(1, tmpLen)
    log.print_debug(logger, "getRandomFromList, listLen:[%s], requestCount:[%s], mpRand:[%s]" % (tmpLen, tmpCount, tmpRand))
    
    f = tmpLen - tmpCount
    e = tmpLen - tmpRand
    b = tmpCount - e
    
    tmpKeys =  tmpList
    tmpReturn = [] 
    if tmpRand > f:
        tmpReturn = tmpKeys[tmpRand:]+ tmpKeys[:b]
    else:
        tmpReturn = tmpKeys[tmpRand: (tmpLen+b)]
    return tmpReturn
    

def getSomeItemFromDict(oldDict, *itemNames):
    '''获取某些字典字段, 返回一个新字典'''
    tmpDict = {}
    for item in itemNames:
        tmpDict[item] = oldDict.get(item)
    return tmpDict

#--------
def inserList(parmList, val):
    '''把值插入某列表中(保证不重复)'''
    if isinstance(parmList, list):
        if val not in parmList:
            parmList.append(val)
            return True
	return False
            
#--------
def deleteFromList(parmList, val):
    '''把值从某列表中删除'''
    if isinstance(parmList, list):
        if val in parmList:
            parmList.remove(val)
            return True
    return False
       
#--------     
def deleteFromDict(parmDict, valKey):
    '''把值从某字典中删除'''
    if isinstance(parmDict, dict) and parmDict.has_key(valKey): 
        parmDict.pop(valKey)        

#--------
def getValByScale(tmpOldVal, tmpScale):
    '''根据比例返回数值'''
    return int((tmpScale + 100) * tmpOldVal / 100)

#--------
def jsonDecode(str):
    '''解码字符串成json对象'''   
    try:
        return json_decode(str)
    except Exception:
        return json_decode(str.decode('gb2312'))

def jsonDecodeToDict(str):
    '''解码字符串成json对象字典''' 
    if str is None or len(str) < 2:
        str = "{}"
    return json_decode(str)

def jsonDecodeToList(str):
    '''解码字符串成json对象队列''' 
    if str is None or len(str) < 2:
        str = "[]"
    return json_decode(str) 

def jsonDecodePerListItemToDict(tmpList, tmpItemNameList):
    '''把数组tmpList的 项 在数组tmpItemNameList的字段 转换成 字典对象'''
    for tmpItemName in tmpItemNameList:
        tmpVal = tmpList.get(tmpItemName)
        tmpList[tmpItemName] = jsonDecodeToDict(tmpVal)     #字符串转换成json字典对象
        
def jsonDecodePerListItemToList(tmpList, tmpItemNameList):
    '''把数组tmpList的 项 在数组tmpItemNameList的字段 转换成 字典对象'''
    for tmpItemName in tmpItemNameList:
        tmpVal = tmpList.get(tmpItemName)
        tmpList[tmpItemName] = jsonDecodeToList(tmpVal)     #字符串转换成json数组对象

def setPerListItemToStr(tmpList, tmpItemNameList):
    '''把数组tmpList的 项 在数组tmpItemNameList的字段 转换成  字符串'''
    for tmpItemName in tmpItemNameList:
        tmpVal = tmpList.get(tmpItemName)
        if tmpVal is None:
            tmpVal = ""
        tmpList[tmpItemName] = str(tmpVal)     #转换字符串
    
def setPerListItemToInt(tmpList, tmpItemNameList):
    '''把数组tmpList的 项 在数组tmpItemNameList的字段 转换成 Int'''
    for tmpItemName in tmpItemNameList:
        tmpVal = tmpList.get(tmpItemName)
        if tmpVal is None:
            tmpVal = 0
        tmpList[tmpItemName] = int(tmpVal)     #转换字符串

def ifListValInOtherList(sourceList, targetList):
    '''判断sourceList的值 是否在  targetList出现过'''
    for tmpItem in sourceList:
        if tmpItem in targetList:
            return True
    return False

def getUrl(url):
    '''同步获取url内容'''
    f = urllib2.urlopen(url)
    res = f.read()
    print res
    return res

def postUrl(url,params):
    '''同步POST url'''
    params = urllib.urlencode(params)
    f = urllib.urlopen(url, params)
    res = f.read()
    print res
    return res

def asynOpenUrl(url, method='GET', body=None, callback=None, **kwargs):
    '''异步调用url   body为字典'''
    if body:
        body = urllib.urlencode(body)
    handler = httpclient.AsyncHTTPClient()
    handler.fetch(url, method=method, body=body, callback=callback, **kwargs)

#排序数字，数组的格式 list = [{"a":1},{"b":2}]
def sortArrDict(tmpList,col,sc='asc'):
    tmpList.sort(lambda x, y: cmp(x.get(col), y.get(col)))     
    tmpList = sorted(tmpList, key=lambda x:x.get(col))     
    if sc == 'desc':
        l = []
        for v in reversed(tmpList):
            l.append(v)
        tmpList = l 
    return tmpList

def rander(percent):
	'''取机率percent 为1~100内的数'''
	percent = int(percent)
	one = random.randint(1, 100)
	total = range(100);
	tmpRange = [];
	i=0
	while i<percent:
		tmpRange.append( total[i])
		i+=1
    
	for v in tmpRange:
		if one==v:
			return True
	return False

def listShuffle(tmpList):
    '''将数组顺序打乱'''
    if tmpList:
        random.shuffle(tmpList)    

#--wudi-2012.03.02
def randomRandInt(sNum, eNum):  #从 sNum 和 eNumb 之间随机取一个整数
    return random.randint(sNum, eNum)

#----单例----
class SingleClass:
    def __init__(self):
        print "SingleClass __init__" 

    @classmethod
    def instance(cls): 
        if not hasattr(cls, "_instance"):
            cls._instance = cls()
        return cls._instance
    
    
#--------------
class Timer:
    '''定时器'''
    def __init__(self, id, func, mstime = 100, loop_count = -1, parms=None):
        self.m_stop = False             #True:表示停止        
        self.m_id = id
        
        if func is None:
            func = self.run_null
        self.m_func = func
        
        self.m_exec_time = mstime       #多少毫秒执行一次
        self.m_loop_count = loop_count  #循环次数 -1表示无限循环
        self.m_begin_time = time.time() #开始时间
        self.m_parms = parms
    
    def run_null(self):
        pass
        
    def run(self, tempCurrentTime):
        if self.m_stop:
            return False
                    
        tempTime = tempCurrentTime - self.m_begin_time
        tempTimeOther = tempTime - self.m_exec_time
                
        if self.m_loop_count == -1:
            if tempTime >= self.m_exec_time:
                log.print_debug(logger, "Timer exec, timer_id:[%s]" % self.m_id)
                self.m_begin_time = tempCurrentTime - tempTimeOther
                self.m_func()
            return True
        
        if self.m_loop_count > 0:
            if tempTime >= self.m_exec_time:
                log.print_debug(logger, "Timer exec, timer_id:[%s]" % self.m_id)
                self.m_begin_time = tempCurrentTime - tempTimeOther
                self.m_loop_count -= 1
                self.m_func(self.m_parms)
            return True
        
        self.m_stop = True
        return False

#--------------
class TimerManager(SingleClass):
    '''定时器管理类'''
        
    s_id = 0
    s_map_timer_manager = {}
    
    def __init__(self):
        pass
    
    def add_timer(self, func, mstime = 100, loop_count = -1, parms=None):
        TimerManager.s_id += 1
        tmpID = TimerManager.s_id
        tmpObj = Timer(tmpID, func, mstime, loop_count, parms) #新建立一个定时器对象
        TimerManager.s_map_timer_manager[tmpID] = tmpObj
        log.print_debug(logger, "TimerManager add_timer, timer_id:[%s]" % tmpID)
        return TimerManager.s_id

    def run(self):        
        tempCurrentTime = time.time()
        for tmpID, obj in TimerManager.s_map_timer_manager.items():            
            if obj is None or obj.m_stop:
                del TimerManager.s_map_timer_manager[tmpID]
                continue
            if not obj.run(tempCurrentTime):
                del TimerManager.s_map_timer_manager[tmpID]
                continue
    
    def delete(self, id):
        if TimerManager.s_map_timer_manager.has_key(id):
            log.print_debug(logger, "TimerManager del_timer, timer_id:[%s]" % id)
            del TimerManager.s_map_timer_manager[id]
  

#--------------
class SendMsgUtil():
    '''发送消息辅助类'''
    
    def __init__(self, request):
        self.m_res_dict =  {"res":"success", "msg":"成功"}
        self.m_request = request
    
    def add_item(self, key, val):
        '''增加字段'''
        self.m_res_dict[key] = val
    
    def add_dict(self, tmpDict):
        '''增加一个字典'''
        self.m_res_dict.update(tmpDict)
        
    def update_item(self, key, val):
        '''修改字段'''
        self.m_res_dict[key] = val
        
    def delete_item(self, key):
        if self.m_res_dict.has_key(key):
            self.m_res_dict.pop(key)
        
    def update_res(self, code, msg = None):
        '''修改结构码'''
        self.m_res_dict["res"] = code        
        if msg is None:
            msg = code_define.get_error(code)            
        self.m_res_dict["msg"] = msg
    
    def getEncodeContent(self):
        '''获取编码后的内容'''
        return json_encode(self.m_res_dict)       
    
    def send(self, cmd='', request=None, callback=None, msg=None):
        '''调用request发送数据'''     
        log.print_debug(logger, "SendMsgUtil send exec---[0]---cmd[%s]---------------------" % cmd)
                       
        tmpStr = msg
        if not msg:
            tmpStr = json_encode(self.m_res_dict)
        tmpRequest = request
        if tmpRequest is None:
            tmpRequest = self.m_request 
            if tmpRequest is None:
                log.print_warning(logger, "SendMsgUtil send exec, request is null")
                return
        log.print_debug(logger, "SendMsgUtil send exec---[1]---cmd[%s]---------------------" % cmd)
        tmpRequest.write(tmpStr, cmd, callback)
        print "@1@send>", cmd, tmpStr
        
        #tmpRequest.finish() #-注:方法finish可以不调用        
        log.print_debug(logger, "SendMsgUtil send exec---[2]---cmd[%s]---------------------" % cmd)

        import user
        user.UserManager.editMapHearBeatTime(tmpRequest) #修改上次发送消息的时间

#--------------
#----配置文件管理器----
class ConfigManager(SingleClass):
    s_map_config_level = {}     #等级信息 {"level": info}
    s_map_config_logic = {}     #逻辑数值配置{name: info}

    def __init__(self):
        pass
   
    @staticmethod
    def reloadConfig():
        ConfigManager.reloadConfigLevel()
        ConfigManager.reloadConfigLogic()
        ConfigManager.reloadOther()
                
        #import const
        #ConfigManager.s_map_config_logic = const.Config_Map_Logic #从配置文件获取
    
    @staticmethod
    def reloadConfigLevel():
        '''加载等级信息'''
        ConfigManager.s_map_config_level.clear()      #清空
        
        from mysqlHelper import mysql        
        conn = mysql()
        sql = "SELECT * FROM t_config_level"            
        tableInfo = conn.getAll(sql)       
        for row in tableInfo:                   
            ConfigManager.s_map_config_level[row['level']] = row
            
        log.print_debug(logger, "ConfigManager reloadConfigLevel exec, info:\n%s" % ConfigManager.s_map_config_level)
    
    @staticmethod
    def reloadConfigLogic():
        '''加载逻辑信息'''
        ConfigManager.s_map_config_logic.clear()      #清空
        
        from mysqlHelper import mysql        
        conn = mysql()
        sql = "SELECT * FROM t_config_logic"            
        tableInfo = conn.getAll(sql)       
        for row in tableInfo:  
            tmpName = row['name']
            tmpName = tmpName.strip()               
            ConfigManager.s_map_config_logic[tmpName] = row
        
        log.print_debug(logger, "ConfigManager reloadConfigLogic exec, info:\n%s" % ConfigManager.s_map_config_logic)
      
    @staticmethod
    def reloadOther():
        '''加载其它逻辑信息'''
        
        const.Config_User_Login_Gift.clear()      #清空
        const.Config_User_Login_Gift["yellow_reg_info_for_girl"] = ConfigManager.getConfigLogicRemark("yellow_reg_info_for_girl")
        const.Config_User_Login_Gift["yellow_reg_info_for_boy"] = ConfigManager.getConfigLogicRemark("yellow_reg_info_for_boy")
        const.Config_User_Login_Gift["yellow_reg_gold_for_girl"] = ConfigManager.getConfigLogic("yellow_reg_gold_for_girl")
        const.Config_User_Login_Gift["yellow_reg_gold_for_boy"] = ConfigManager.getConfigLogic("yellow_reg_gold_for_boy")
        const.Config_User_Login_Gift["yellow_reg_other_for_girl"] = ConfigManager.getConfigLogicRemarkToList("yellow_reg_other_for_girl")
        const.Config_User_Login_Gift["yellow_reg_other_for_boy"] = ConfigManager.getConfigLogicRemarkToList("yellow_reg_other_for_boy")
        
        const.Config_User_Login_Gift["yellow_day_info_for_girl"] = ConfigManager.getConfigLogicRemark("yellow_day_info_for_girl")
        const.Config_User_Login_Gift["yellow_day_info_for_boy"] = ConfigManager.getConfigLogicRemark("yellow_day_info_for_boy")
        const.Config_User_Login_Gift["yellow_day_gold_for_girl"] = ConfigManager.getConfigLogic("yellow_day_gold_for_girl")
        const.Config_User_Login_Gift["yellow_day_gold_for_boy"] = ConfigManager.getConfigLogic("yellow_day_gold_for_boy")
        const.Config_User_Login_Gift["yellow_day_other_for_girl"] = ConfigManager.getConfigLogicRemarkToList("yellow_day_other_for_girl")
        const.Config_User_Login_Gift["yellow_day_other_for_boy"] = ConfigManager.getConfigLogicRemarkToList("yellow_day_other_for_boy")
         
        const.Config_User_Login_Gift["day_info_for_girl"] = ConfigManager.getConfigLogicRemark("day_info_for_girl")
        const.Config_User_Login_Gift["day_info_for_boy"] = ConfigManager.getConfigLogicRemark("day_info_for_boy")
        const.Config_User_Login_Gift["day_gold_for_girl"] = ConfigManager.getConfigLogic("day_gold_for_girl")
        const.Config_User_Login_Gift["day_gold_for_boy"] = ConfigManager.getConfigLogic("day_gold_for_boy")
        const.Config_User_Login_Gift["day_other_for_girl"] = ConfigManager.getConfigLogicRemarkToList("day_other_for_girl")
        const.Config_User_Login_Gift["day_other_for_boy"] = ConfigManager.getConfigLogicRemarkToList("day_other_for_boy")
      
    @staticmethod  
    def getConfigLogic(name):
        '''获取配置信息other字段值'''
        tmpLogic = ConfigManager.s_map_config_logic.get(name)
        if tmpLogic:
            tmpVal = tmpLogic.get("other")
            if tmpVal is None:
                tmpVal = 0
            return int(tmpVal)
        return 0
    
    @staticmethod  
    def getConfigLogicRemark(name):
        '''获取配置信息remark字段值'''
        tmpLogic = ConfigManager.s_map_config_logic.get(name)
        if tmpLogic:
            tmpVal = tmpLogic.get("remark")
            if tmpVal is None:
                tmpVal = ""
            return tmpVal
        return ""
    
    @staticmethod  
    def getConfigLogicRemarkToList(name):
        '''获取配置信息remark字段值  编码成列表对象'''
        tmpLogic = ConfigManager.s_map_config_logic.get(name)
        if tmpLogic is None:
            return []
        tmpVal = tmpLogic.get("remark")
        return jsonDecodeToList(tmpVal)
    
    @staticmethod  
    def getConfigLogicRemarkToDict(name):
        '''获取配置信息remark字段值  编码成字典对象'''
        tmpLogic = ConfigManager.s_map_config_logic.get(name)
        if tmpLogic is None:
            return {}
        tmpVal = tmpLogic.get("remark")
        return jsonDecodeToDict(tmpVal)
        
    @staticmethod
    def getLevelInfo(level):
        '''获取某等级对应的数值'''
        return ConfigManager.s_map_config_level.get(level)
    
    @staticmethod
    def getLevelByExp(val):
        '''根据经验值计算等级'''
        tmpLevel = 1
        for level, info in ConfigManager.s_map_config_level.items():
            if val >= info["exp"]:
                tmpLevel = level
            else:
                break
        return tmpLevel 
    
    @staticmethod
    def getValueByLevel(level, type):
        '''根据等级获取相应的数值(等级不存在，获取最大等级的经验值)''' 
        tmpMap = ConfigManager.s_map_config_level
        tmpLen = len(tmpMap) 
        if level > len(tmpMap): #获取最后一个等级信息
            level = tmpLen
        if level < 1:
            level = 1
        tmpLeveInfo = tmpMap.get(level)
        if tmpLeveInfo: 
            return tmpLeveInfo.get(type) 
        return 0
    
    
    
    @staticmethod
    def getExpByLevel(level):
        '''获取某等级对应的经验值'''
        return ConfigManager.getValueByLevel(level, "exp")
        
    @staticmethod
    def getCourageByLevel(level):
        '''获取某等级对应的勇气值'''
        return ConfigManager.getValueByLevel(level, "courage")
    
    @staticmethod
    def getQualityByLevel(level):
        '''获取某等级对应的人品值'''
        return ConfigManager.getValueByLevel(level, "quality")
    
    @staticmethod
    def getEnergyByLevel(level):
        '''获取某等级对应的人缘值(精力)'''
        return ConfigManager.getValueByLevel(level, "energy")
    
    #20120228新增口才、知识、体质、情绪、样貌
    @staticmethod
    def getEloquenceByLevel(level):
        '''获取某等级对应的口才值'''
        return ConfigManager.getValueByLevel(level, "eloquence")
    
    @staticmethod
    def getKnowledgeByLevel(level):
        '''获取某等级对应的知识值'''
        return ConfigManager.getValueByLevel(level, "knowledge")
    
    @staticmethod
    def getConstitutionByLevel(level):
        '''获取某等级对应的体质值'''
        return ConfigManager.getValueByLevel(level, "constitution")
    
    @staticmethod
    def getMoodByLevel(level):
        '''获取某等级对应的情绪值'''
        return ConfigManager.getValueByLevel(level, "mood")
    
    @staticmethod
    def getAppearanceByLevel(level):
        '''获取某等级对应的样貌值'''
        return ConfigManager.getValueByLevel(level, "appearance")
    
    
    @staticmethod
    def getEnergyByLevelDistance(level):
        '''获取某等级 和前一等奖 人缘值(精力)的差值'''
        if level == 1:
            return 0
        tmpV_pre = ConfigManager.getValueByLevel(level-1, "energy")
        tmpV = ConfigManager.getValueByLevel(level, "energy")
        return tmpV - tmpV_pre
    
    #20120229新增
    @staticmethod
    def getEloquenceByLevelDistance(level):
        '''获取某等级 和前一等奖 人缘值(口才)的差值'''
        if level == 1:
            return 0
        tmpV_pre = ConfigManager.getValueByLevel(level-1, "eloquence")
        tmpV = ConfigManager.getValueByLevel(level, "eloquence")
        return tmpV - tmpV_pre
    @staticmethod
    def getKnowledgeByLevelDistance(level):
        '''获取某等级 和前一等奖 人缘值(知识)的差值'''
        if level == 1:
            return 0
        tmpV_pre = ConfigManager.getValueByLevel(level-1, "knowledge")
        tmpV = ConfigManager.getValueByLevel(level, "knowledge")
        return tmpV - tmpV_pre
    @staticmethod
    def getConstitutionByLevelDistance(level):
        '''获取某等级 和前一等奖 人缘值(体质)的差值'''
        if level == 1:
            return 0
        tmpV_pre = ConfigManager.getValueByLevel(level-1, "constitution")
        tmpV = ConfigManager.getValueByLevel(level, "constitution")
        return tmpV - tmpV_pre
    @staticmethod
    def getMoodByLevelDistance(level):
        '''获取某等级 和前一等奖 人缘值(情绪)的差值'''
        if level == 1:
            return 0
        tmpV_pre = ConfigManager.getValueByLevel(level-1, "mood")
        tmpV = ConfigManager.getValueByLevel(level, "mood")
        return tmpV - tmpV_pre
    @staticmethod
    def getAppearanceByLevelDistance(level):
        '''获取某等级 和前一等奖 人缘值(外貌)的差值'''
        if level == 1:
            return 0
        tmpV_pre = ConfigManager.getValueByLevel(level-1, "appearance")
        tmpV = ConfigManager.getValueByLevel(level, "appearance")
        return tmpV - tmpV_pre
    
    
    
    @staticmethod
    def getRemarkByLevel(level):
        '''获取某等级对应的赠送的物品'''
        tmpVal = ConfigManager.getValueByLevel(level, "remark")
        return jsonDecodeToList(tmpVal) #返回数组对象(该等级赠送的物品)
    
    @staticmethod
    def getGiftGoodsListByLevel(level):
        '''获取某等级礼包对应的子商品列表'''
        tmpVal = ConfigManager.getValueByLevel(level, "gift_goods_list")
        return jsonDecodeToList(tmpVal) #返回数组对象
    
    @staticmethod
    def getLogicInfo(name):
        '''根据配置名，获取配置项'''
        tmpItem = ConfigManager.s_map_config_logic.get(name)
        if tmpItem:
            return tmpItem.copy()
        else:
            log.print_warning(logger, "getLogicInfo exec, logicName['%s'] is not exists" % name) 
            tmpDict = {"exp":0, "gold":0, "money":0, "courage":0, "power":0, "quality":0, "charm":0, "eloquence":0, "knowledge":0, "constitution":0, "mood":0, "appearance":0}
            return tmpDict
        
    @staticmethod
    def getLogicInfoVal(configName, itemName):
        '''获取配置项 的某字段值'''
        tmpDict = ConfigManager.getLogicInfo(configName)
        tmpVal = tmpDict.get(itemName)
        if tmpVal is None:
            tmpVal = 0
        return tmpVal
    
    @staticmethod
    def setLogicInfoVal(logicMapObj, type, val, bNegative=False):
        '''修改配置项 (参数, bNegative:是否修改为负数)'''
        if logicMapObj:
            tmpVal = val
            if bNegative:
                tmpVal = -abs(val)
            logicMapObj[type] = tmpVal

    @staticmethod
    def setLogicInfoVal_gift_goods_list(logicMapObj, goods_list):
        '''设置配置项(要赠送的商品)'''
        if logicMapObj and isinstance(goods_list, list):
            logicMapObj["gift_goods_list"] = goods_list
        
    @staticmethod
    def setLogicInfoExt(logicMapObj, valMultiple):
        '''修改配置项 , 每项乘倍数 (参数, 倍数)'''
        if logicMapObj:
            for k, v in logicMapObj.items():
                logicMapObj[k] = v*valMultiple
            
    @staticmethod
    def setLogicInfoVal_Gold(logicMapObj, val, bNegative=False):
        '''修改配置项-金币'''
        ConfigManager.setLogicInfoVal(logicMapObj, "gold", val, bNegative)
    
    @staticmethod
    def setLogicInfoVal_Money(logicMapObj, val, bNegative=False):
        '''修改配置项-比索'''
        ConfigManager.setLogicInfoVal(logicMapObj, "money", val, bNegative)
      
    @staticmethod
    def setLogicInfoVal_Exp(logicMapObj, val, bNegative=False):
        '''修改配置项-经验'''
        ConfigManager.setLogicInfoVal(logicMapObj, "exp", val, bNegative) 
      
    @staticmethod
    def setLogicInfoVal_Courage(logicMapObj, val, bNegative=False):
        '''修改配置项-勇气'''
        ConfigManager.setLogicInfoVal(logicMapObj, "courage", val, bNegative)

    @staticmethod
    def setLogicInfoVal_Quality(logicMapObj, val, bNegative=False):
        '''修改配置项-人品'''
        ConfigManager.setLogicInfoVal(logicMapObj, "quality", val, bNegative)
        
    @staticmethod
    def setLogicInfoVal_Energy(logicMapObj, val, bNegative=False):
        '''修改配置项-人缘'''
        ConfigManager.setLogicInfoVal(logicMapObj, "energy", val, bNegative)
 
    @staticmethod
    def setLogicInfoVal_Charm(logicMapObj, val, bNegative=False):
        '''修改配置项-魅力'''
        ConfigManager.setLogicInfoVal(logicMapObj, "charm", val, bNegative)
        
    @staticmethod
    def setLogicInfoVal_Eloquence(logicMapObj, val, bNegative=False):
        '''修改配置项-口才'''
        ConfigManager.setLogicInfoVal(logicMapObj, "eloquence", val, bNegative)
        
    @staticmethod
    def setLogicInfoVal_Knowledge(logicMapObj, val, bNegative=False):
        '''修改配置项-知识'''
        ConfigManager.setLogicInfoVal(logicMapObj, "knowledge", val, bNegative)
        
    @staticmethod
    def setLogicInfoVal_Constitution(logicMapObj, val, bNegative=False):
        '''修改配置项-体质'''
        ConfigManager.setLogicInfoVal(logicMapObj, "constitution", val, bNegative)
        
    @staticmethod
    def setLogicInfoVal_Mood(logicMapObj, val, bNegative=False):
        '''修改配置项-情绪'''
        ConfigManager.setLogicInfoVal(logicMapObj, "mood", val, bNegative)
        
    @staticmethod
    def setLogicInfoVal_Appearance(logicMapObj, val, bNegative=False):
        '''修改配置项-样貌'''
        ConfigManager.setLogicInfoVal(logicMapObj, "appearance", val, bNegative)
        
  

#--------------
class CountUserUtil:
    '''计算用户数值'''
    def __init__(self):  
        pass                  
#        tmp_gold = tmpUser.getUserInfo("gold");                 # 金币
#        tmp_money = tmpUser.getUserInfo("money");               # 比索   
#        tmp_Exp = tmpUser.getUserInfo("exp")                     # 经验
#        
#        tmp_energy = tmpUser.getUserInfo("energy")               # 精力(人缘)     
#           
#        tmp_courage = tmpUser.getUserInfo("courage")             # 勇气(消耗值,可自动恢复) 
#        tmp_quality = tmpUser.getUserInfo("quality")             # 人品 (消耗值,可自动恢复)
#        tmp_courage_time = tmpUser.getUserInfo("courage_time")   # 勇气值更新时间
#        tmp_quality_time = tmpUser.getUserInfo("quality_time")   # 人品值更新时间
        
    @staticmethod
    def _countValueByTime(tmpUser, type):
        '''根据时间计算用户数值（勇气值,人品值), 返回最新值，最新值对应的时间'''
        tmpNewValue = 0
        tmpNewEditTime = time.time()  #当前时间
        import const
        
        if tmpUser:
            tmpLevel = tmpUser.getLevel()
            tmpMax = ConfigManager.getValueByLevel(tmpLevel, type)  #该等级对应的数值
            tmpOldVal =  tmpUser.getUserInfoToInt(type)             #老数值
            
            if type == "power":
                tmpMax = const.Config_MaxPower() #最大体力值
            
            if tmpOldVal >= tmpMax:     #旧值超过当前等级最大值, 则返回旧值，及当前时间
                tmpNewValue = tmpOldVal
            else:
                tmpPerTime = 1
                tmpStr = ""
                if type == "courage":
                    tmpPerTime = const.Config_RecoverCouragePerTime() #多少秒恢复一点勇气值
                    tmpStr = "courage_time"
                elif type == "power":
                    tmpPerTime = const.Config_RecoverPowerPerTime() #多少秒恢复一点体力值
                    tmpStr = "power_time"
                else:
                    tmpPerTime = const.Config_RecoverQualityPerTime() #多少秒恢复一点人品值
                    tmpStr = "quality_time"                
                if not tmpPerTime:
                    tmpPerTime = 1
                
                tmpOldEditTime = tmpUser.getUserInfoToInt(tmpStr)       #上次修改时间
            
                tmpIntervalTime = int(tmpNewEditTime - tmpOldEditTime)  #时间间隔(秒)
                tmpRecover = (tmpIntervalTime / tmpPerTime)             #恢复的数值  (时间间隔/多少秒)
                tmpNewValue = tmpRecover + tmpOldVal                    #当前新数值
                
                if tmpNewValue < 0:
                    tmpNewValue = 0
                if tmpNewValue > tmpMax:
                    tmpNewValue = tmpMax
                
                tmpNewEditTime -= (tmpIntervalTime % tmpPerTime)  #更新时间
            
        return int(tmpNewValue), int(tmpNewEditTime) 
    
    @staticmethod
    def getCurrentCourage(tmpUser):
        '''计算用户当前勇气值'''
        return CountUserUtil._countValueByTime(tmpUser, "courage")[0]

    @staticmethod
    def getCurrentPower(tmpUser):
        '''计算用户当前体力值'''
        return CountUserUtil._countValueByTime(tmpUser, "power")[0]
        
    @staticmethod
    def getCurrentQuality(tmpUser):
        '''计算用户当前人品值'''
        return CountUserUtil._countValueByTime(tmpUser, "quality")[0]
       
    @staticmethod
    def isEnough(tmpUser, type, newVal):
        '''数值是否足够(用户对象，类型，新数值)'''
        if not tmpUser:
            return False
        tmpVal= tmpUser.getUserInfoToInt(type);
        if tmpVal + newVal < 0:
            return False
        return True
    
    @staticmethod
    def isGoldEnough(tmpUser, newVal):
        '''金币值是否足够'''
        return CountUserUtil.isEnough(tmpUser, "gold", newVal)
       
    @staticmethod
    def isMoneyEnough(tmpUser, newVal):
        '''比索值是否足够'''
        return CountUserUtil.isEnough(tmpUser, "money", newVal)
    
    @staticmethod
    def isCourageEnough(tmpUser, newVal):
        '''勇气值是否足够'''
        tmpVal = CountUserUtil.getCurrentCourage(tmpUser)
        if tmpVal + newVal < 0:
            return False
        return True

    @staticmethod
    def isPowerEnough(tmpUser, newVal):
        '''体力值是否足够'''
        tmpVal = CountUserUtil.getCurrentPower(tmpUser)
        if tmpVal + newVal < 0:
            return False
        return True
    
    @staticmethod
    def isQualityEnough(tmpUser, newVal):
        '''人品值是否足够'''
        tmpVal = CountUserUtil.getCurrentQuality(tmpUser)
        if tmpVal + newVal < 0:
            return False
        return True
		
    @staticmethod
    def isEnergyEnough(tmpUser, newVal):
        '''人缘值是否足够'''
        return CountUserUtil.isEnough(tmpUser, "energy", newVal)
    
    
    @staticmethod
    def isEloquenceEnough(tmpUser, newVal):
        '''口才值是否足够'''
        return CountUserUtil.isEnough(tmpUser, "eloquence", newVal)
    
    @staticmethod
    def isKnowledgeEnough(tmpUser, newVal):
        '''知识值是否足够'''
        return CountUserUtil.isEnough(tmpUser, "knowledge", newVal)
    
    @staticmethod
    def isConstitutionEnough(tmpUser, newVal):
        '''体质值是否足够'''
        return CountUserUtil.isEnough(tmpUser, "constitution", newVal)
    
    @staticmethod
    def isMoodEnough(tmpUser, newVal):
        '''情绪值是否足够'''
        return CountUserUtil.isEnough(tmpUser, "mood", newVal)
    
    @staticmethod
    def isAppearanceEnough(tmpUser, newVal):
        '''样貌值是否足够'''
        return CountUserUtil.isEnough(tmpUser, "appearance", newVal)
    
        
    @staticmethod
    def pushUserNumber(tmpUser, sourceCmd="push_user_value", bUpLevel=False, **parms):
        '''push用户数值变化'''
        if tmpUser:
            cmd = "push_user_value"
            request = tmpUser.getRequest()
            tmpSendMsgUtil = SendMsgUtil(request)     #消息发送器
            
            tmpLevel = tmpUser.getLevel()
            tmpNextLevel = tmpLevel + 1
            
            tmpChangeItems = {}
            tmpItems = {}
            
            for name, addVal in parms.items():
                if addVal == 0: #变动值为0, 则不返还
                    continue
                
                tmpChangeItems[name] = addVal   #有变动
                tmpItems[name] = tmpUser.getUserInfoToInt(name)
                
                if name == "courage":   #该等级最大的勇气值
                    tmpItems["max_courage"] = ConfigManager.getCourageByLevel(tmpLevel)  #达到当前等级最大的勇气
                    tmpItems["next_courage"] = ConfigManager.getCourageByLevel(tmpNextLevel)  #达到下一等级的勇气  
                    
                if name == "power":
                    tmpItems["max_power"] = const.Config_MaxPower() #最大体力值
                    
                if name == "quality":   #该等级最大的人品值 
                    tmpItems["max_quality"] = ConfigManager.getQualityByLevel(tmpLevel)  #达到当前等级最大的人品
                    tmpItems["next_quality"] = ConfigManager.getQualityByLevel(tmpNextLevel)  #达到下一等级的人品
                    
                if name == "energy":   #该等级最大的人品值 
                    tmpItems["max_energy"] = tmpUser.getCurrentMaxEnergy()                    #达到当前等级最大的人缘 
                    tmpItems["next_energy"] = ConfigManager.getEnergyByLevel(tmpNextLevel)    #达到下一等级的人缘
                                
                if name == "level":     #等级变化
                    tmpItems["level"] = tmpUser.getUserInfoToInt("level")    #等级
                    tmpItems["courage"] = tmpUser.getUserInfoToInt("courage")#勇气
                    tmpItems["power"] = tmpUser.getUserInfoToInt("power")    #体力
                    tmpItems["quality"] = tmpUser.getUserInfoToInt("quality")#人品 
                    tmpItems["energy"] = tmpUser.getEnergy()                 #人缘
                     
                    tmpItems["level_exp"] = ConfigManager.getExpByLevel(tmpLevel)       #达到当前等级的最低经验值        
                    tmpItems["next_exp"] = ConfigManager.getExpByLevel(tmpNextLevel)    #达到下一等级的经验值 
                    
                    tmpItems["max_courage"] = ConfigManager.getCourageByLevel(tmpLevel)  #达到当前等级最大的勇气
                    tmpItems["next_courage"] = ConfigManager.getCourageByLevel(tmpNextLevel)  #达到下一等级的勇气
                    
                    tmpItems["max_power"] = const.Config_MaxPower() #最大体力值
                    
                    tmpItems["max_quality"] = ConfigManager.getQualityByLevel(tmpLevel)  #达到当前等级最大的人品
                    tmpItems["next_quality"] = ConfigManager.getQualityByLevel(tmpNextLevel)  #达到下一等级的人品
                    
                    tmpItems["max_energy"] = tmpUser.getCurrentMaxEnergy()                    #达到当前等级最大的人缘 
                    tmpItems["next_energy"] = ConfigManager.getEnergyByLevel(tmpNextLevel)    #达到下一等级的人缘
                    
                    #20120228新增
                    tmpItems["max_eloquence"] = ConfigManager.getEloquenceByLevel(tmpLevel)         #达到当前等级最大的口才 
                    tmpItems["next_eloquence"] = ConfigManager.getEloquenceByLevel(tmpNextLevel)    #达到下一等级的口才
                    
                    tmpItems["max_knowledge"] = ConfigManager.getKnowledgeByLevel(tmpLevel)         #达到当前等级最大的知识 
                    tmpItems["next_knowledge"] = ConfigManager.getKnowledgeByLevel(tmpNextLevel)    #达到下一等级的知识
                    
                    tmpItems["max_constitution"] = ConfigManager.getConstitutionByLevel(tmpLevel)         #达到当前等级最大的体质 
                    tmpItems["next_constitution"] = ConfigManager.getConstitutionByLevel(tmpNextLevel)    #达到下一等级的体质
                    
                    tmpItems["max_mood"] = ConfigManager.getMoodByLevel(tmpLevel)         #达到当前等级最大的情绪
                    tmpItems["next_mood"] = ConfigManager.getMoodByLevel(tmpNextLevel)    #达到下一等级的情绪
                    
                    tmpItems["max_appearance"] = ConfigManager.getAppearanceByLevel(tmpLevel)         #达到当前等级最大的样貌 
                    tmpItems["next_appearance"] = ConfigManager.getAppearanceByLevel(tmpNextLevel)    #达到下一等级的样貌
                    
                    if bUpLevel:   #升级
                        #from home import home
                        tmpItems["max_steal_gold"] = 0 #home.get_roomer_config_steal_gold(tmpLevel)#当前等级可被偷的金币最大值
                    
                        tmpGoodsList = ConfigManager.getRemarkByLevel(tmpLevel) #新等级要送的物品
                        tmpItems["level_send_goods"] = tmpGoodsList
                    
            tmpSendMsgUtil.add_item("user", tmpItems)           #用户当前值           
            tmpSendMsgUtil.add_item("change", tmpChangeItems)   #变化的值
            tmpSendMsgUtil.add_item("cmd", sourceCmd)           #来源命令字
            tmpSendMsgUtil.send(cmd)
 
    @staticmethod
    def _editUserVal(tmpUser, name, addVal): 
        '''更新用户缓存, (非负数)'''
        if not tmpUser:
            return 0       
        tmpNewVal = tmpUser.getUserInfoToInt(name) 
        tmpNewVal += addVal
        if tmpNewVal < 0:
            tmpNewVal = 0 
        tmpUser.setUserInfo(name, tmpNewVal)
        return tmpNewVal 
    
    @staticmethod
    def _editUserValByTime(tmpUser, name, timeVal, addVal, editTime): 
        '''更新用户缓存, timeVal:最新值, addVal:增减值, editTime:最新值对应时间'''
        if not tmpUser:
            return 0
        
        tmpNewVal = timeVal 
        tmpNewVal += addVal            
        if tmpNewVal < 0:
            tmpNewVal = 0
        tmpUser.setUserInfo(name, tmpNewVal)
        
        if name == "courage": 
            tmpUser.setUserInfo("courage_time", editTime)
        elif name == "power": 
            tmpUser.setUserInfo("power_time", editTime)
        elif name == "quality": 
            tmpUser.setUserInfo("quality_time", editTime)
            
        return tmpNewVal
            
    @staticmethod
    def _editUserValChangeLevel(tmpUser, name, tmpNewVal, oldLevel, newLevel): 
        '''等级变化时， 更新用户[勇气, 人品, 人缘]缓存, tmpNewVal:最新值'''
        if not tmpUser:
            return 0
        
        if oldLevel < newLevel:  #升级
            tmpMax = ConfigManager.getValueByLevel(newLevel, name)      #该等级对应的数值
            if tmpNewVal < tmpMax:  #升级, 小于最大值, 则满值
                tmpNewVal = tmpMax 
                
        tmpUser.setUserInfo(name, tmpNewVal)                
        return tmpNewVal
        
    @staticmethod
    def _editUserValByTimeChangeLevel(tmpUser, name, tmpNewVal, editTime, oldLevel, newLevel): 
        '''等级变化时，更新用户[勇气, 人品]缓存, timeVal:最新值, editTime:最新值对应时间''' 
        if not tmpUser:
            return 0
        if name == "courage": 
            tmpUser.setUserInfo("courage_time", editTime)
        elif name == "quality": 
            tmpUser.setUserInfo("quality_time", editTime)
            
        return CountUserUtil._editUserValChangeLevel(tmpUser, name, tmpNewVal, oldLevel, newLevel)
        
    @staticmethod
    def _editUserEnergyChangeLevel(tmpUser, oldLevel, newLevel): 
        '''等级变化时，更新用户[人缘]缓存'''
        if not tmpUser:
            return 0
        tmpNewVal = tmpUser.getEnergy() 
        
        if oldLevel < newLevel:  #升级, 最新人缘=人缘+等级差值
            tmpDictinct = ConfigManager.getEnergyByLevelDistance(newLevel)
            tmpNewVal += tmpDictinct
            
        tmpUser.setUserInfo("energy", tmpNewVal)  
        return tmpNewVal 
        #return CountUserUtil._editUserValChangeLevel(tmpUser, "energy", tmpNewVal, oldLevel, newLevel)
        
        
    # 20120229新增   
    @staticmethod
    def _editUserEloquenceChangeLevel(tmpUser, oldLevel, newLevel): 
        '''等级变化时，更新用户[口才]缓存'''
        if not tmpUser:
            return 0
        tmpNewVal = tmpUser.getEloquence() 
        
        if oldLevel < newLevel:  #升级, 最新人缘=人缘+等级差值
            tmpDictinct = ConfigManager.getEloquenceByLevelDistance(newLevel)
            tmpNewVal += tmpDictinct
            
        tmpUser.setUserInfo("eloquence", tmpNewVal)  
        return tmpNewVal
    @staticmethod
    def _editUserKnowledgeChangeLevel(tmpUser, oldLevel, newLevel): 
        '''等级变化时，更新用户[知识]缓存'''
        if not tmpUser:
            return 0
        tmpNewVal = tmpUser.getKnowledge() 
        
        if oldLevel < newLevel:  #升级, 最新人缘=人缘+等级差值
            tmpDictinct = ConfigManager.getKnowledgeByLevelDistance(newLevel)
            tmpNewVal += tmpDictinct
            
        tmpUser.setUserInfo("knowledge", tmpNewVal)  
        return tmpNewVal
    @staticmethod
    def _editUserConstitutionChangeLevel(tmpUser, oldLevel, newLevel): 
        '''等级变化时，更新用户[体质]缓存'''
        if not tmpUser:
            return 0
        tmpNewVal = tmpUser.getConstitution() 
        
        if oldLevel < newLevel:  #升级, 最新人缘=人缘+等级差值
            tmpDictinct = ConfigManager.getConstitutionByLevelDistance(newLevel)
            tmpNewVal += tmpDictinct
            
        tmpUser.setUserInfo("constitution", tmpNewVal)  
        return tmpNewVal
    @staticmethod
    def _editUserMoodChangeLevel(tmpUser, oldLevel, newLevel): 
        '''等级变化时，更新用户[情绪]缓存'''
        if not tmpUser:
            return 0
        tmpNewVal = tmpUser.getMood() 
        
        if oldLevel < newLevel:  #升级, 最新人缘=人缘+等级差值
            tmpDictinct = ConfigManager.getMoodByLevelDistance(newLevel)
            tmpNewVal += tmpDictinct
            
        tmpUser.setUserInfo("mood", tmpNewVal)  
        return tmpNewVal
    @staticmethod
    def _editUserAppearanceChangeLevel(tmpUser, oldLevel, newLevel): 
        '''等级变化时，更新用户[样貌]缓存'''
        if not tmpUser:
            return 0
        tmpNewVal = tmpUser.getAppearance() 
        
        if oldLevel < newLevel:  #升级, 最新人缘=人缘+等级差值
            tmpDictinct = ConfigManager.getAppearanceByLevelDistance(newLevel)
            tmpNewVal += tmpDictinct
            
        tmpUser.setUserInfo("appearance", tmpNewVal)  
        return tmpNewVal

    @staticmethod
    def judgeUserGameValueEnough(cmd, request, tmpUser, bInLine, bPushErrorMsg=True, exp=0, gold=0, money=0, courage=0, power=0, quality=0, energy=0, charm=0, cloth_charm=0,eloquence=0, knowledge=0, constitution=0,mood=0, appearance=0):
        '''判断数值是否够'''
        if not tmpUser:
            return False

        #------判断是否够, 不够则返回错误码
        errorCode = "success"
        while True:
            #-金币
            if gold < 0 and not CountUserUtil.isGoldEnough(tmpUser, gold):
                errorCode = "not_gold"
                break
            #-比索
            if money < 0 and not CountUserUtil.isMoneyEnough(tmpUser, money):
                errorCode = "not_money"
                break
            #-勇气
            if courage < 0 and not CountUserUtil.isCourageEnough(tmpUser, courage):
                errorCode = "not_courage"
                break
            
            #-体力
            if power < 0 and not CountUserUtil.isPowerEnough(tmpUser, power):
                errorCode = "not_power"
                break
            
            #-人品
            if quality < 0 and not CountUserUtil.isQualityEnough(tmpUser, quality):
                errorCode = "not_quality"
                break
            #-人缘
            if energy < 0 and not CountUserUtil.isEnergyEnough(tmpUser, energy):
                errorCode = "not_energy"
                break
            
            #20120228新增
            #-人缘
            if energy < 0 and not CountUserUtil.isEloquenceEnough(tmpUser, energy):
                errorCode = "not_eloquence"
                break
            #-人缘
            if energy < 0 and not CountUserUtil.isKnowledgeEnough(tmpUser, energy):
                errorCode = "not_knowledge"
                break
            #-人缘
            if energy < 0 and not CountUserUtil.isConstitutionEnough(tmpUser, energy):
                errorCode = "not_constitution"
                break
            #-人缘
            if energy < 0 and not CountUserUtil.isMoodEnough(tmpUser, energy):
                errorCode = "not_mood"
                break
            #-人缘
            if energy < 0 and not CountUserUtil.isAppearanceEnough(tmpUser, energy):
                errorCode = "not_appearance"
                break
            break
        
        if errorCode == "success":
            return True
         
        if bInLine and bPushErrorMsg:  #---数值不够并且在线，且可以push错误信息, 则 发送数值不够消息
            tmpSendMsgUtil = SendMsgUtil(request)  #消息发送器
            tmpSendMsgUtil.update_res(errorCode)
            tmpSendMsgUtil.send(cmd)
        return False    
        
    @staticmethod
    def judgeUserGameValueEnoughExt(cmd, request, uid, configLogicName, bPushErrorMsg=True):
        '''configLogicName: 配置map对象或配置名称,  bPushErrorMsg:错误时, 是否直接push错误信息'''
        configLogicMapItem = configLogicName
        if not isinstance(configLogicMapItem, dict):#参数传入的不是配置字典对象, 则读取配置项
            configLogicMapItem = ConfigManager.getLogicInfo(configLogicName) #获取配置项            
            
        import user
        bInLine = True     #用户是否在线
        tmpUser = user.UserManager.get_user_by_uid(uid)
        if not tmpUser:  #用户不在线
            bInLine = False
            newUserinfo = user.UserManager.get_user_game_info(uid)    #查询DB数据
            tmpUser = user.User(0, newUserinfo, None)
            
        return CountUserUtil.judgeUserGameValueEnough(cmd, request, tmpUser, bInLine, bPushErrorMsg,
                                   exp = configLogicMapItem.get("exp"), 
                                   gold = configLogicMapItem.get("gold"), 
                                   money = configLogicMapItem.get("money"), 
                                   courage = configLogicMapItem.get("courage"), 
                                   power = configLogicMapItem.get("power"), 
                                   quality = configLogicMapItem.get("quality"), 
                                   energy = configLogicMapItem.get("energy"),
                                   charm = configLogicMapItem.get("charm"),
                                   eloquence = configLogicMapItem.get("eloquence"),
                                   knowledge = configLogicMapItem.get("knowledge"),
                                   constitution = configLogicMapItem.get("constitution"),
                                   mood = configLogicMapItem.get("mood"),
                                   appearance = configLogicMapItem.get("appearance"),
                                   cloth_charm = 0)
        
    @staticmethod
    def judgeAndEditExt(cmd, request, uid, configLogicName, bJudge=True, bPushErrorMsg=True):
        '''configLogicName: 配置map对象或配置名称, bJudge:是否判断数值足够, bPushErrorMsg:错误时, 是否直接push错误信息'''
        configLogicMapItem = configLogicName
        if not isinstance(configLogicMapItem, dict):#参数传入的不是配置字典对象, 则读取配置项
            configLogicMapItem = ConfigManager.getLogicInfo(configLogicName) #获取配置项            
        return CountUserUtil.judgeAndEdit(cmd, request, uid, bJudge, bPushErrorMsg,
                                   exp = configLogicMapItem.get("exp"), 
                                   gold = configLogicMapItem.get("gold"), 
                                   money = configLogicMapItem.get("money"), 
                                   courage = configLogicMapItem.get("courage"), 
                                   power = configLogicMapItem.get("power"), 
                                   quality = configLogicMapItem.get("quality"), 
                                   energy = configLogicMapItem.get("energy"),
                                   charm = configLogicMapItem.get("charm"),                                   
                                   cloth_charm = 0, 
                                   parmsGiftGoodsList = configLogicMapItem.get("gift_goods_list", []),
                                   eloquence = configLogicMapItem.get("eloquence"),
                                   knowledge = configLogicMapItem.get("knowledge"),
                                   constitution = configLogicMapItem.get("constitution"),
                                   mood = configLogicMapItem.get("mood"),
                                   appearance = configLogicMapItem.get("appearance")
                                   )

    @staticmethod
    def judgeAndEdit(cmd, request, uid, bJudge=True, bPushErrorMsg=True, exp=0, gold=0, money=0, 
                     courage=0, power=0, quality=0, energy=0, charm=0, cloth_charm=0, parmsGiftGoodsList=[],eloquence=0, knowledge=0, constitution=0,mood=0, appearance=0):
        '''判断数值是否够， 不够发错误码， 够则扣数值， 并更新DB, push数值变化'''
        import user
        from mysqlHelper import mysql        
        conn = mysql()
            
        bInLine = True     #用户是否在线
        tmpUser = user.UserManager.get_user_by_uid(uid)
        if not tmpUser:  #用户不在线
            bInLine = False
            newUserinfo = user.UserManager.get_user_game_info(uid)    #查询DB数据
            tmpUser = user.User(0, newUserinfo, None)
        
        #--判断数值是否足够, 不够， 则发错误码， 并返回
        if not CountUserUtil.judgeUserGameValueEnough(cmd, request, tmpUser, bInLine, bPushErrorMsg,
                                                       exp, gold, money, courage, power, quality, energy, charm,
                                                       cloth_charm,
                                                       eloquence, knowledge, constitution,mood, appearance):
            return False
         
        editDataMap = {} 
        
        #------数值够----扣数值---
        #-金币
        name = "gold"
        editDataMap[name] = CountUserUtil._editUserVal(tmpUser, name, gold)#增减值, 并更新用户缓存
        #-比索
        if money != 0:
            name = "money"
            editDataMap[name] = CountUserUtil._editUserVal(tmpUser, name, money)#增减值, 并更新用户缓存 
        #-勇气
        if courage != 0:
            name = "courage"
            newVal, newEditTime = CountUserUtil._countValueByTime(tmpUser, name)#获取最新值, 及最新时间
            editDataMap[name] = CountUserUtil._editUserValByTime(tmpUser, name, newVal, courage, newEditTime)#增减值, 并更新用户缓存
            editDataMap["courage_time"] = newEditTime

        #-体力
        if power != 0:
            name = "power"
            newVal, newEditTime = CountUserUtil._countValueByTime(tmpUser, name)#获取最新值, 及最新时间
            editDataMap[name] = CountUserUtil._editUserValByTime(tmpUser, name, newVal, power, newEditTime)#增减值, 并更新用户缓存
            editDataMap["power_time"] = newEditTime
            
        #-人品
        if quality != 0:
            name = "quality"
            newVal, newEditTime = CountUserUtil._countValueByTime(tmpUser, name)#获取最新值, 及最新时间
            editDataMap[name] = CountUserUtil._editUserValByTime(tmpUser, name, newVal, quality, newEditTime)#增减值, 并更新用户缓存
            editDataMap["quality_time"] = newEditTime
        #-人缘
        if energy != 0:
            name = "energy"
            editDataMap[name] = CountUserUtil._editUserVal(tmpUser, name, energy)#增减值, 并更新用户缓存
        
        #-魅力        
        if charm != 0:
            name = "charm"
            editDataMap[name] = CountUserUtil._editUserVal(tmpUser, name, charm) #增减值, 并更新用户缓存 
        #-衣服魅力
        if cloth_charm != 0:
            name = "cloth_charm"
            editDataMap[name] = CountUserUtil._editUserVal(tmpUser, name, cloth_charm)  #增减值, 并更新用户缓存
            
        #-口才
        if eloquence != 0:           
            name = "eloquence"
            editDataMap[name] = CountUserUtil._editUserVal(tmpUser, name, eloquence)  #增减值, 并更新用户缓存
        #-知识
        if knowledge != 0:
            name = "knowledge"
            editDataMap[name] = CountUserUtil._editUserVal(tmpUser, name, knowledge)  #增减值, 并更新用户缓存
        #-体质
        if constitution != 0:
            name = "constitution"
            editDataMap[name] = CountUserUtil._editUserVal(tmpUser, name, constitution)  #增减值, 并更新用户缓存
        #-情绪
        if mood != 0:
            name = "mood"
            editDataMap[name] = CountUserUtil._editUserVal(tmpUser, name, mood)  #增减值, 并更新用户缓存
        #-外貌
        if appearance != 0:
            name = "appearance"
            editDataMap[name] = CountUserUtil._editUserVal(tmpUser, name, appearance)  #增减值, 并更新用户缓存
        
        #--赠送的商品列表
        if len(parmsGiftGoodsList):
            from store import store
            store.send_goods_to_somebody(tmpUser, parmsGiftGoodsList)     #送礼, 修改缓存, 修改DB
            
        
        #-经验(升级、降级会影响用户的勇气值和人品， 人缘)
        newLevel = 0        #最新等级
        changeLevel = 0     #等级的改变
        bUpLevel = False    #是否升级
        if exp != 0:
            name = "exp"
            tmpNewExp = CountUserUtil._editUserVal(tmpUser, name, exp)  #增减值, 并更新用户缓存
            editDataMap[name] = tmpNewExp  #当前新经验
            
            #--等级--
            name = "level"
            oldLevel = tmpUser.getUserInfoToInt(name)
            newLevel = ConfigManager.getLevelByExp(tmpNewExp) #根据最新经验值获取等级
            changeLevel = newLevel - oldLevel   #等级变化
            
            if newLevel != oldLevel:  #等级有变化-----------------
                tmpUser.setUserInfo(name, newLevel)#更新用户缓存
                editDataMap[name] = newLevel
                
                newCourageVal, newCourageEditTime = CountUserUtil._countValueByTime(tmpUser, "courage")#获取最新值, 及最新时间
                newQualityVal, newQualityEditTime = CountUserUtil._countValueByTime(tmpUser, "quality")#获取最新值, 及最新时间
                     
                #勇气, 人品随着等级变化更新, 并更新缓存
                editDataMap["courage"] = CountUserUtil._editUserValByTimeChangeLevel(tmpUser, "courage", newCourageVal, newCourageEditTime, oldLevel, newLevel)
                editDataMap["quality"] = CountUserUtil._editUserValByTimeChangeLevel(tmpUser, "quality", newQualityVal, newQualityEditTime, oldLevel, newLevel)
                    
                editDataMap["courage_time"] = newCourageEditTime #编辑时间 
                editDataMap["quality_time"] = newQualityEditTime
                
                #人缘更新, 并更新缓存
                editDataMap["energy"] = CountUserUtil._editUserEnergyChangeLevel(tmpUser, oldLevel, newLevel)
                
                editDataMap["eloquence"] = CountUserUtil._editUserEloquenceChangeLevel(tmpUser, oldLevel, newLevel)
                editDataMap["knowledge"] = CountUserUtil._editUserKnowledgeChangeLevel(tmpUser, oldLevel, newLevel)
                editDataMap["constitution"] = CountUserUtil._editUserConstitutionChangeLevel(tmpUser, oldLevel, newLevel)
                editDataMap["mood"] = CountUserUtil._editUserMoodChangeLevel(tmpUser, oldLevel, newLevel)
                editDataMap["appearance"] = CountUserUtil._editUserAppearanceChangeLevel(tmpUser, oldLevel, newLevel)
                
                
                if newLevel > oldLevel:  #升级 , 1)被偷金币加满, 2)赠送物品  
                    bUpLevel = True    #是否升级
                    from home import * 
                    #home.EditStealGoldByLevel(newLevel, uid) #升级, 被偷金币加满--更改DB表 t_user_record----
                    tmpGoodsList = ConfigManager.getRemarkByLevel(newLevel) #新等级要送的物品 
                    #from store import store
                    store.send_goods_to_somebody(tmpUser, tmpGoodsList)     #送礼, 修改缓存, 修改DB
        
        
        #---------更改DB表t_user_data
        conn.upData("t_user_data", editDataMap, " where uid = %s " % uid)   #更新db
        
        #---------更改DB表 t_log_value_change
        tmpData = {"current": editDataMap}
        sql = "insert into t_log_value_change(type_name, timeline, uid, nickname, data) values('%s', now(), '%s', '%s', '%s');" % (cmd, uid, tmpUser.getNickname(), json_encode(tmpData))
        #conn.query(sql)
        SqlThread.addSqlStr(sql) #线程写记录
        
        #---------更改DB表 t_log_total_everyday (金币赠送或消耗)
        user.UserManager.updateLogTotalEveryday(cmd, gold, money)
        
        if bInLine:     #在线, 发送数值变化消息
            CountUserUtil.pushUserNumber(tmpUser, sourceCmd=cmd, bUpLevel=bUpLevel,  
                                         gold=gold, money=money, 
                                         courage=courage, power=power, quality=quality, 
                                         exp=exp, level=changeLevel, energy=energy, 
                                         charm=charm, cloth_charm=cloth_charm, gift_goods_list=parmsGiftGoodsList,
                                         eloquence=eloquence,knowledge=knowledge,constitution=constitution,mood=mood,appearance=appearance
                                         )
        else:
            del tmpUser #不在线, 删除临时用户对象
        
        return True


#---线程写DB记录  
class SqlThread(threading.Thread):
    s_queue = Queue.Queue() #队列, 保存sql语句
    
    def __init__(self):
        threading.Thread.__init__(self)
              
    def run(self):
        try:
            while True:
                if SqlThread.s_queue.qsize() > 0:           #队列有数据,则执行，否则休眠1秒
                    tmpStrSql = SqlThread.s_queue.get()     #get有锁,线程安全
                    log.print_debug(logger, "SqlThread sql exec, sql:%s," % tmpStrSql)
                    
                    from mysqlHelper import mysql        
                    conn = mysql()
                    conn.query(tmpStrSql)   #执行sql
                else:
                    print "SqlThread----------sleep"
                    time.sleep(1)
        except Exception:
            log.print_error(logger, 'SqlThread, run error:\n%s' % traceback.format_exc())

    @staticmethod
    def addSqlStr(tmpStrSql):
        '''保存sql语句到队列'''
        log.print_debug(logger, "SqlThread sql exec, sql:%s," % tmpStrSql)
        SqlThread.s_queue.put(tmpStrSql)    #有锁,线程安全


##===========以下为测试单例类的方法=========================================
#class Test(SingleClass):
#    i = 0
#    def __init__(self):
#        print "test.__init__-----------."
#        Test.i += 1
#        SingleClass.__init__(self)
#       
#    def show(self):
#        print "i m Test i: %s" % Test.i
#    
#Test.instance().show()    
#a = Test.instance()
#a.show()
#b = Test.instance()
#b.show()
#
#if a is b:
#    print "a == b"    
##====================================================

#-------测试随机获取----
#tmpMap = {"1":"a", "2":"aa", "3":"aaa", "4":"aaaa", "5":"aaaaa", "6":"aaaaaa"}        
#
#print getKeysFromMap(tmpMap, 2)
#print getKeysFromMap(tmpMap, 4)
#print getKeysFromMap(tmpMap, 6)


##-------测试获取字典某字段----------
#oldDict = {"a":1, "b":2, "c":3, "d":4}
#print getSomeItemFromDict(oldDict, "a", "d", "e")    
